<script setup>
import { ref, watch, provide, h } from 'vue'
import api from '@/api/index.js'
import MyTable from '@/components/MyTable/MyTable.vue'
import { Modal } from 'ant-design-vue'
import { message } from 'ant-design-vue'

const emits = defineEmits(['init', 'reload', 'close'])
const props = defineProps({
  curRow: {
    type: Object,
    default: () => ({})
  }
})

// 弹窗标题
const title = '详情'
// 表单数据
const formData = ref({})
const tableData = ref([])

// 获取表格数据的函数
const fetchTableData = async (id) => {
  if (id) {
    // 按钮类型的父节点id为数组，需要特殊处理
    const {
      data: { records }
    } = await api.getCsxq({ size: 99999, id })
    tableData.value = records
  }
}

// 监听 curRow 变化并获取数据
watch(
  () => props.curRow,
  async (val) => {
    await fetchTableData(val.id)
  },
  { deep: true, immediate: true }
)

// 是否显示弹窗
const show = ref(false)
// 弹窗显示状态切换时触发
const afterOpenChange = (bool) => {
  if (!bool) {
    formData.value = {}
    emits('reload')
    emits('close')
  }
}
// 打开弹窗
const open = () => {
  show.value = true
}
defineExpose({ open })

// 表格列配置
const columns = ref([
  { ellipsis: false, title: '商品名称', dataIndex: 'productName', key: 'productName' },
  { ellipsis: false, title: '规格型号', dataIndex: 'specs', key: 'specs' },
  { ellipsis: false, title: '计量单位', dataIndex: 'unit', key: 'unit' },
  { ellipsis: false, title: '新增数量', dataIndex: 'currentSell', key: 'currentSell' },
  { ellipsis: false, title: '操作', key: 'set', width: '200px', align: 'center' }
])

// 删除数据
const del = (item) => {
  Modal.warning({
    title: '删除农资数据',
    content: h('span', {}, '删除后起所有数据都将被清空'),
    okText: '删除',
    okCancel: true,
    okButtonProps: { type: 'primary', danger: true },
    cancelButtonProps: { type: 'primary' },
    cancelText: '取消',
    onOk: async () => {
      await api.delCsXq({ id: item.id })
      message.success('删除成功')
      await fetchTableData(props.curRow.id) // 删除成功后重新获取数据
      return Promise.resolve()
    },
    onCancel: () => {
      message.success('取消删除')
      return Promise.resolve()
    }
  })
}

provide('columns', columns.value)
provide('tableData', tableData)
</script>

<template>
  <a-drawer
    :maskClosable="false"
    :closable="false"
    destroyOnClose
    v-model:open="show"
    class="custom-class"
    root-class-name="root-class-name"
    :title="title"
    placement="right"
    @after-open-change="afterOpenChange"
    width="1200px"
  >
    <MyTable :pagination="false" :scroll="{ y: 'calc(100vh - 383px)' }">
      <template #bodyCell="{ column, record }">
        <!-- <template v-if="column.key === 'set'">
          <AButton type="link" class="com-delbtn" @click="del(record)">删除</AButton>
        </template> -->
      </template>
    </MyTable>
    <template #footer>
      <div style="display: flex; gap: 5px">
        <a-button type="primary" ghost @click="show = false">关闭</a-button>
      </div>
    </template>
  </a-drawer>
</template>
